package com.wl.dzt.sys.core.dao.curd.mysql;

import com.wl.dzt.sys.core.dao.curd.CrudConvert;
import com.wl.dzt.sys.core.dao.curd.CrudConvertResult;
import com.wl.dzt.sys.core.dao.select.Select;
import com.wl.dzt.sys.core.dao.select.SelectMate;
import com.wl.dzt.sys.core.dao.select.SelectSqlBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author wl_code@163.com
 * @date 2018/7/5/005
 * @version 1.0
 * @description mysql转换
 * 
 */
@Component
public class CrudConvertForMysql implements CrudConvert {

	/**
	 * mysql查询构建器
	 */
	@Resource
	private SelectSqlBuilder selectSqlBuilderForMysql;

	/**
	 * <b>mysql查询转换</b>
	 * <p>
	 * 根据mysql的语法特性转换查询语句
	 * </p>
	 * 
	 * @param select
	 * @return
	 */
	public CrudConvertResult selectConvert(Select select) {
		CrudConvertResult convertResult = new CrudConvertResult();
		SelectMate selectMate = selectSqlBuilderForMysql.assembleAll(select);
		convertResult.setArgs(selectMate.getArgs().toArray());
		convertResult.setSql(select.getLimit() > 0 ? selectMate.toPageSql() : selectMate.toSql());
		return convertResult;
	}

	/**
	 * <b>mysql 查询总数转换</b>
	 * <p>
	 *  根据mysql的语法特性转换总数查询语句
	 * </p>
	 * 
	 * @param select
	 * @return
	 */
	public CrudConvertResult countConvert(Select select) {
		CrudConvertResult convertResult = new CrudConvertResult();
		SelectMate selectMate = selectSqlBuilderForMysql.assembleAll(select);
		convertResult.setSql(selectMate.toCountSql());
		convertResult.setArgs(selectMate.getArgs().toArray());
		return convertResult;
	}

	public void changeSelectSqlBuilderForMysql(SelectSqlBuilderForMysql builderForMysql) {
		this.selectSqlBuilderForMysql = builderForMysql;
	}

	/**
	 * <b>获取分页sql模板</b>
	 * <p>
	 * 其中参数位置用%s表示
	 * </p>
	 * 
	 * @return
	 */
	public String getPageTemplate() {
		return " (%s) limit %s , %s ";
	}

}
